/**
 * Created by zhaocong on 2016/7/12.
 * 基于jq,上传图片组件,上传完成后返回服务器上的一个地址
 */
define(function (require, exports, module) {
  "use strict";
  var cc = window.cc || {};

  /**
   * 初始化上传组件
   * @param url 上传地址
   * @param bin 按钮
   */
  cc.imageReset = function (url, bin) {
    var tmp = document.createElement('iframe');
    tmp.id = 'tmpIframe';
    tmp.name = 'tmpIframe';
    tmp.style.display = 'none';
    document.body.appendChild(tmp);

    $(bin).each(function (i, el) {
      $(el).attr('data-file', i);
      var form = document.createElement('form');
      form.className = 'tmpFileForm tmp' + i;
      form.action = url;
      form.method = "post";
      form.target = "tmpIframe";
      form.enctype = "multipart/form-data";
      form.style.display = 'none';
      document.body.appendChild(form);

      var azFile = document.createElement("input");
      azFile.name = "azFile";
      azFile.className = 'azFile';
      azFile.id = 'file' + i;
      azFile.type = "file";
      azFile.accept = "image/*";
      $('.tmp' + i)[0].appendChild(azFile);
    });
  };


  /**
   * 表单页面
   * @param url
   * @constructor
   */
  cc.Imageupload = function (url) {
    var self = this;

    var bin = '.sz-imgup';
    cc.imageReset(url, bin);

    /**
     * 上传图片
     */
    self.imgUp = function () {
      var $this = $(this),
          fileId = $this.data('file'),
          file = $('#file' + fileId);
      file.trigger('click');
      file.on('change', function () {
        $('.tmp' + fileId).submit();
        $this.html('<i class="fa fa-refresh fa-spin fa-fw"></i>');
      });
      $('#tmpIframe').on('load', function () {
        $this.removeClass('btn-warning').addClass('btn-success').html('<i class="fa fa-check-circle"></i> 上传成功');
        $this.next().val($.trim($(window.frames['tmpIframe'].document.body).html()));
      });
    };

    $('.sz-imgup').on('click', self.imgUp);
  };

  /**
   * 多图上传
   * zxxFile.js 基于HTML5 文件上传的核心脚本
   * http://www.zhangxinxu.com/wordpress/?p=1923
   */
  cc.ZXXFILE = {
    fileInput: null,				//html file控件
    dragDrop: null,					//拖拽敏感区域
    upButton: null,					//提交按钮
    url: "",						//ajax地址
    fileFilter: [],					//过滤后的文件数组
    filter: function (files) {		//选择文件组的过滤方法
      return files;
    },
    onSelect: function () {
    },		//文件选择后
    onDelete: function () {
    },		//文件删除后
    onDragOver: function () {
    },		//文件拖拽到敏感区域时
    onDragLeave: function () {
    },	//文件离开到敏感区域时
    onProgress: function () {
    },		//文件上传进度
    onSuccess: function () {
    },		//文件上传成功时
    onFailure: function () {
    },		//文件上传失败时,
    onComplete: function () {
    },		//文件全部上传完毕时

    /* 开发参数和内置方法分界线 */

    //文件拖放
    funDragHover: function (e) {
      e.stopPropagation();
      e.preventDefault();
      this[e.type === "dragover" ? "onDragOver" : "onDragLeave"].call(e.target);
      return this;
    },
    //获取选择文件，file控件或拖放
    funGetFiles: function (e) {
      // 取消鼠标经过样式
      this.funDragHover(e);

      // 获取文件列表对象
      var files = e.target.files || e.dataTransfer.files;
      //继续添加文件
      this.fileFilter = this.fileFilter.concat(this.filter(files));
      this.funDealFiles();
      return this;
    },

    //选中文件的处理与回调
    funDealFiles: function () {
      for (var i = 0, file; file = this.fileFilter[i]; i++) {
        //增加唯一索引值
        file.index = i;
      }
      //执行选择回调
      this.onSelect(this.fileFilter);
      return this;
    },

    //删除对应的文件
    funDeleteFile: function (fileDelete) {
      var arrFile = [];
      for (var i = 0, file; file = this.fileFilter[i]; i++) {
        if (file != fileDelete) {
          arrFile.push(file);
        } else {
          this.onDelete(fileDelete);
        }
      }
      this.fileFilter = arrFile;
      return this;
    },

    //文件上传
    funUploadFile: function () {
      var self = this;
      if (location.host.indexOf("sitepointstatic") >= 0) {
        //非站点服务器上运行
        return;
      }
      for (var i = 0, file; file = this.fileFilter[i]; i++) {
        (function (file) {
          var xhr = new XMLHttpRequest();
          if (xhr.upload) {
            // 上传中
            xhr.upload.addEventListener("progress", function (e) {
              self.onProgress(file, e.loaded, e.total);
            }, false);

            // 文件上传成功或是失败
            xhr.onreadystatechange = function (e) {
              if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                  self.onSuccess(file, xhr.responseText);
                  self.funDeleteFile(file);
                  if (!self.fileFilter.length) {
                    //全部完毕
                    self.onComplete();
                  }
                } else {
                  self.onFailure(file, xhr.responseText);
                }
              }
            };
            // 开始上传
            xhr.open("POST", self.url, true);
            xhr.setRequestHeader("X_FILENAME", file.name);
            xhr.send(file);
          }
        })(file);
      }
    },

    init: function () {
      var self = this;
      if (this.dragDrop) {
        this.dragDrop.addEventListener("dragover", function (e) {
          self.funDragHover(e);
        }, false);
        this.dragDrop.addEventListener("dragleave", function (e) {
          self.funDragHover(e);
        }, false);
        this.dragDrop.addEventListener("drop", function (e) {
          self.funGetFiles(e);
        }, false);
      }
      //文件选择控件选择
      if (this.fileInput) {
        this.fileInput.addEventListener("change", function (e) {
          self.funGetFiles(e);
        }, false);
      }
      //上传按钮提交
      if (this.upButton) {
        this.upButton.addEventListener("click", function (e) {
          self.funUploadFile(e);
        }, false);
      }
    }
  };

  /**
   * 多图上传
   * @param url
   * @constructor
   */
  cc.Params = function (url) {
    var self = this;
    var ZXXFILE = cc.ZXXFILE;

    /**
     * 初始化swiper 依赖swiper控件
     */
    var swiper = new Swiper('.swiper-container', {
      pagination: '.swiper-pagination',
      paginationClickable: '.swiper-pagination',
      mousewheelControl: true,
      mousewheelReleaseOnEdges: true,
      autoplay: 2000
    });

    /**
     * 弹出上传图片组件
     * @type {string}
     */
    var imagesInput = '';
    $('#imageUpbtn').click(function () {
      $('#imageUpModal').modal();
      imagesInput = $(this).next();
    });

    /**
     * 每次上传成功一张图片，就添加到swiper中，并且将返回的数组存放到input中
     * @param response
     */
    var imageArr = [];
    self.imageOver = function (response) {
      imageArr.push(response);
      imagesInput.val(imageArr);
      swiper.appendSlide('<div class="swiper-slide" style="background: url(' + response + ') no-repeat center/cover;"><i class="fa fa-close swiper-close" data-id="response"></i></div>');
      swiper.startAutoplay();
    };

    $('.swiper-container').on('click', '.swiper-slide .swiper-close', function () {
      swiper.removeSlide(swiper.activeIndex);
      imageArr.splice(imageArr.indexOf($(this).data('id')), 1);
      imagesInput.val(imageArr);
    });

    /**
     * 上传图片
     */
    var params = {
      url: url,
      fileInput: $('#fileImage').get(0),
      dragDrop: $('#fileDragArea').get(0),
      upButton: $("#fileSubmit").get(0),
      filter: function (files) {
        var arrFiles = [];
        for (var i = 0, file; file = files[i]; i++) {
          if (file.type.indexOf("image") == 0) {
            if (file.size >= 5120000) {
              alert('您这张"' + file.name + '"图片大小过大，应小于5mb');
            } else {
              arrFiles.push(file);
            }
          } else {
            alert('文件"' + file.name + '"不是图片。');
          }
        }
        return arrFiles;
      },
      onSelect: function (files) {
        var html = '', i = 0;
        $("#preview").html('<div class="upload_loading"></div>');
        var funAppendImage = function () {
          var file = files[i];
          if (file) {
            var reader = new FileReader()
            reader.onload = function (e) {
              html = html + '<div id="uploadList_' + i + '" class="upload_append_list"><p><span>' + file.name + '</span>' +
                  '<a href="javascript:" class="upload_delete" title="删除" data-index="' + i + '">删除</a><br />' +
                  '<img id="uploadImage_' + i + '" src="' + e.target.result + '" class="upload_image" /></p>' +
                  '<span id="uploadProgress_' + i + '" class="upload_progress"></span>' +
                  '</div>';

              i++;
              funAppendImage();
            }
            reader.readAsDataURL(file);
          } else {
            $("#preview").html(html);
            if (html) {
              //删除方法
              $(".upload_delete").click(function () {
                ZXXFILE.funDeleteFile(files[parseInt($(this).attr("data-index"))]);
                return false;
              });
              //提交按钮显示
              $("#fileSubmit").show();
            } else {
              //提交按钮隐藏
              $("#fileSubmit").hide();
            }
          }
        };
        funAppendImage();
      },
      onDelete: function (file) {
        $("#uploadList_" + file.index).hide();
      },
      onDragOver: function () {
        $(this).addClass("upload_drag_hover");
      },
      onDragLeave: function () {
        $(this).removeClass("upload_drag_hover");
      },
      onProgress: function (file, loaded, total) {
        var eleProgress = $("#uploadProgress_" + file.index), percent = (loaded / total * 100).toFixed(2) + '%';
        eleProgress.show().html(percent);
      },
      onSuccess: function (file, response) {
        // 上传成功
        self.imageOver(response);
      },
      onFailure: function (file) {
        $("#uploadInf").append("<p>图片" + file.name + "上传失败！</p>");
        $("#uploadImage_" + file.index).css("opacity", 0.2);
      },
      onComplete: function () {
        //提交按钮隐藏
        $("#fileSubmit").hide();
        //file控件value置空
        $("#fileImage").val("");
        $("#uploadInf").append("<p>当前图片全部上传完毕，可继续添加上传。</p>");
        // 彻底完成
        $('#imageUpModal').modal('hide');
      }
    };
    ZXXFILE = $.extend(ZXXFILE, params);
    ZXXFILE.init();
  };

  module.exports = cc;
});